package org.swingDemo.worker;

import javax.swing.*;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class MoveFileWorker extends SwingWorker<Void, Void> {

    private File file;
    private String targetFolderName;

    public MoveFileWorker(File file, String targetFolderName) {
        this.file = file;
        this.targetFolderName = targetFolderName;
    }

    @Override
    protected Void doInBackground() throws Exception {
        if (this.file == null || this.targetFolderName == null) {
            return null;
        }

        final File parentFile = file.getParentFile();
        final Path sourcePath = Paths.get(file.getAbsolutePath());
        Path targetPath = Paths.get(parentFile.getAbsolutePath(), targetFolderName);
        final File targetFile = targetPath.toFile();
        // 子目录不存在时创建目录
        if (targetFile == null || !targetFile.isDirectory()) {
            Files.createDirectory(targetPath);
        }
        targetPath = Paths.get(parentFile.getAbsolutePath(), targetFolderName, file.getName());
        Files.move(sourcePath, targetPath);
        return null;
    }
}
